package android.androidapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JsonClient {

	private static String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the BufferedReader.readLine()
		 * method. We iterate until the BufferedReader return null which means
		 * there's no more data to read. Each line will appended to a StringBuilder
		 * and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return sb.toString();
	}

	private static String getHttpResponse(String url)
	{
		HttpClient httpclient = new DefaultHttpClient();

		// Prepare a request object
		HttpGet httpget = new HttpGet(url); 

		// Execute the request
		HttpResponse response;
		try {
			response = httpclient.execute(httpget);
			// Get hold of the response entity
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			// to worry about connection release

			if (entity != null)
			{
				// A Simple JSON Response Read
				InputStream instream = entity.getContent();
				String result= convertStreamToString(instream);
				
				// Closing the input stream will trigger connection release
				//instream.close();
				
				return result;
			}
			else
				return null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			Log.e("ERROR", e.toString());
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.e("ERROR", e.toString());
			return null;
		}
	}

	public static LocationInfo[] getLocationObjects()
	{
			String result = getHttpResponse("http://cop4331.dataloggin.com/service/functions.php?requestType=getAllPOIs").trim();
			if (result != null) 
			{

				try
				{
					//Parse the JSON array
					JSONArray valArray = new JSONArray(result);
					
					LocationInfo[] returnArray = new LocationInfo[valArray.length()];
					
					for(int i=0;i<valArray.length();i++)
					{
						LocationInfo li = new LocationInfo();
						li.id = valArray.getJSONObject(i).getInt("id");
						li.name = valArray.getJSONObject(i).getString("name");
						li.longitude = valArray.getJSONObject(i).getDouble("longitude_custom") * 1E6;
						li.latitude = valArray.getJSONObject(i).getDouble("latitude_custom") * 1E6;
						
						returnArray[i] = li;
					}
					
					return returnArray;
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					Log.e("ERROR", e.toString());
					return null;
				}
				catch (Exception e)
				{
					return null;
				}
			}
			else
				return null;
	}
	
	public static String getEventInformation(int poiID)
	{
			String result = getHttpResponse("http://cop4331.dataloggin.com/service/functions.php?requestType=getSpecificEventDetailsPOI&poiID="+Integer.toString(poiID)).trim();
			if (result != null) 
			{

				try
				{
					if(result.equals("null"))
						return "No events currently at this location.";
					
					//Parse the JSON array
					JSONArray valArray = new JSONArray(result);
					
					String returnString = "";
					
					for(int i=0;i<valArray.length();i++)
					{
						int eventID = valArray.getJSONObject(i).getInt("id");
						String name = valArray.getJSONObject(i).getString("name");
						String description = valArray.getJSONObject(i).getString("description");
						int points = valArray.getJSONObject(i).getInt("points");
						String startDate = valArray.getJSONObject(i).getString("date_start");
						String endDate = valArray.getJSONObject(i).getString("date_end");
						
						returnString += name+" - "+description+"\nPoints Awarded: "+Integer.toString(points)+"\nEvent Start Date: "+startDate+"\nEvent End Date: "+endDate+"\n----";
					}
					
					return returnString;
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					Log.e("ERROR", e.toString());
					return "No events currently at this location.";
				}
				catch (Exception e)
				{
					return "No events currently at this location.";
				}
			}
			else
				return "No events currently at this location.";
	}

	public static int[] getCurrentEventInformationPOIIDs()
	{
			String result = getHttpResponse("http://cop4331.dataloggin.com/service/functions.php?requestType=getCurrentDayEventsPOIID").trim();
			if (result != null) 
			{
				try
				{
					//Parse the JSON array
					JSONArray valArray = new JSONArray(result);
					
					int[] returnArray = new int[valArray.length()];
					
					for(int i=0;i<valArray.length();i++)
					{
						int poiID = valArray.getJSONObject(i).getInt("id_poi");
						returnArray[i] = poiID;
					}
					
					return returnArray;
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					Log.e("ERROR", e.toString());
					return null;
				}
				catch (Exception e)
				{
					return null;
				}
			}
			else
				return null;
	}

}
